<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/23
 * Time: 9:13
 */

namespace app\service;


use app\admin\controller\Member;
use app\alliance\controller\Common;
use PhpCsFixer\ToolInfo;
use Redis\Redis;
use think\App;
use think\Db;

class BusinessService extends Common
{
    private $_Redis;

    function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->_Redis = new Redis();
    }

    /**
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 获取用户生意列表
     */
    function getsMemberBusiness()
    {
        if ($this->memberInfo['super_player'] == 2) {
            return $this->superPlayer();
        } else {
            $list = $this->_Redis->hGetJson("member_business", $this->code);
            if (!empty($list)) {
                return $this->listSettle($list);
            } else {
                return $this->setMemberBusiness();
            }
        }
    }

    /**
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 将用户生意存入缓存
     */
    function setMemberBusiness()
    {
        $list = Db::table("member_business_grid mbg")
            ->field("mbg.id mbg_id,mbg.status open_status,mbg.grid,mbg.sell_business_id,mbg.start_time,mbg.end_time,mbg.pract_end_time,
                           mbg.member_business_id,mb.*,convert(mb.day_income,decimal(10,2)) day_income")
            ->join("member_business mb", "mbg.member_business_id=mb.id and mb.status!=-1", "left")
            ->join("industry indu", "indu.id=mb.industry_id", "left")
            ->where(array("mbg.member_code" => $this->code))
            ->order("mbg.grid asc")
            ->select();
        if (!empty($list)) {
            return $this->listSettle($list);
        } else {
            return false;
        }
    }

    /**
     * @param $list
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 列表信息整理
     */
    function listSettle($list)
    {
        $super_grid = true;
        $super_business = 0;
        $day_income = 0;
        $a = new IGeTuiService();
        foreach ($list as $k => $v) {

            if ($this->memberInfo['member_violations'] == 2) {
                $super_grid = false;
                $super_business = false;
                # 用户账户被锁定 状态改为锁定
                continue;
            }
            if ($v['open_status'] == 0 or $v['open_status'] == 2) {
                $super_grid = false;
                $super_business = false;
                # 未开启状态
                continue;
            } elseif ($v['open_status'] == 1 or $v['open_status'] == 4 or $v['open_status'] == 5 or $v['open_status'] == 7) {

                # 开启中，匹配中或匹配成功 待付款状态 看是否超过3天
                # 判断是否超时3天锁定状态

                if (empty($v['member_business_id'])) {
//                    if($v['pract_end_time']<=date("Y-m-d H:i:s")){
//                       $material_system=$this->_Redis->hGetJson("restore_material_system",$this->code);
//                       if(empty($material_system)){
//                           # 超时锁定状态
//                           $this->memberInfo['member_violations']=2;
//                           Db::table("member")->where(array("code"=>$this->code))->update(array("member_violations"=>2));
//                           $this->_Redis->hSetJson("memberInfo",$this->code,$this->memberInfo);
//                           continue;
//                       }
//                    }
                    if ($v['open_status'] == 5) {
                        # 匹配成功之后 1个小时不确定改为匹配失败
                        $pract_end_time = diffSuspend($v['start_time'], $v['end_time']);
                        $_array = array();
                        if ($v['pract_end_time'] != $pract_end_time) {
                            $v['pract_end_time'] = $pract_end_time;
                            $_array['pract_end_time'] = $pract_end_time;
                        }
                        if (date("Y-m-d H:i:s") >= $v['pract_end_time']) {
                            # 匹配成功超过一个小时 改为匹配失败状态 点进去可重新购买
                            $list[$k]['open_status'] = 1;
                            $list[$k]['start_time'] = $v['pract_end_time'];
                            $list[$k]['end_time'] = date("Y-m-d H:i:s", strtotime("+3 days", strtotime($v['pract_end_time'])));
                            $list[$k]['pract_end_time'] = date("Y-m-d H:i:s", strtotime("+3 days", strtotime($v['pract_end_time'])));
                            $_array['status'] = 1;
                            $_array['start_time'] = $list[$k]['start_time'];
                            $_array['end_time'] = $list[$k]['end_time'];
                            $_array['pract_end_time'] = $list[$k]['pract_end_time'];
                            #  删除匹配信息
                            $this->_Redis->hDel("userMatchBussiness", $this->code . "and" . $v['grid']);
                        }
                        if (!empty($_array)) {
                            Db::table("member_business_grid")->where(array("id" => $v['mbg_id']))->update($_array);
                        }
                    } elseif ($v['open_status'] == 6) {
                        if ($v['end_time'] <= date("Y-m-d H:i:s")) {
                            $success_data = Db::table("trad_audit")
                                ->where(array("industry_id" => $v['sell_business_id'], "is_violations" => 1, "trad_status" => 1))->find();
                            if (!empty($success_data)) {
                                $jobService = new jobService();
                                $jobService->successTrade($success_data);
                            }
                        }
                    } elseif ($v['open_status'] == 7) {
                        if ($v['end_time'] <= date("Y-m-d H:i:s")) {

                            # 查询该生意是否在栏位中
                            $sell_business_info = Db::table("member_business")->where(array("id" => $v['sell_business_id']))->find();
                            $sell_gird_info = Db::table("member_business_grid")
                                ->where(array("member_code" => $sell_business_info['member_code'], "member_business_id" => $v['sell_business_id']))->find();
                            if (!empty($v['sell_business_id'])) {
                                $jobService = new jobService();
                                $jobService->recoverSellStatus($v['sell_business_id'], $sell_gird_info['grid'], $sell_business_info['member_code'], $this->code, $v['grid']);
                            } else {
                                Db::table("member_business_grid")->where(array("member_code" => $this->code, "grid" => $v['grid']))
                                    ->update(array("status" => 1, "sell_business_id" => 0, "member_business_id" => 0));
                            }
                            $list[$k]['open_status'] = 1;
                            $list[$k]['sell_business_id'] = 0;
                            $list[$k]['member_business_id'] = 0;

                        }
                    }
                    continue;
                } else {

                    if ($v['open_status'] == 1) {
                        if ($v['status'] == 1) {
                            # 判断生长周期和交租日期
                            if ($v['growth_cycle'] == $v['rent_day']) {
                                if (date("Y-m-d H:i:s") >= $v['sell_time']) {
                                    # 修改为可出售状态
                                    $list[$k]['status'] = 2;
                                    Db::table("member_business")->where(array("id" => $v['id']))->update(array("status" => 2));
                                    goto cansale;
                                }
                            } else {

                                # 判断是否需要交租
                                $diff = timediff(time(), strtotime($v['buy_time']));

                                if ($diff['day'] == 0) {

                                    # 今日购买的 不需要交租
                                    # 收益中
                                    earn:
                                    $day_income += $v['day_income'];
                                } else {
                                    # 判断今日交租状态
                                    if (date("Y-m-d", strtotime($v['opera_start_time'])) == date("Y-m-d")) {
                                        # 今日已交租
                                        goto earn;
                                    } else {
                                        # 判断距离上次交租过了多少天 (交租后给这个字段改为结束时间的时分秒)
                                        freeze:
                                        $diff_rent = timediff(time(), strtotime($v['opera_start_time']));
//                                        if($diff_rent['day']>$v['growth_cycle']-$v['rent_day']){
//                                            $diff_rent['day']=$v['growth_cycle']-$v['rent_day'];
//                                        }
                                        if ($diff_rent['day'] == 0) {
                                            goto earn;
                                        } elseif ($diff_rent['day'] == 1) {
                                            $newsRemind = $this->_Redis->hGetJson("remindRent", $this->code . "and" . $v['grid']);
                                            if (empty($newsRemind)) {
                                                $_time = strtotime(date("Y-m-d 23:59:59")) - time();
                                                $this->_Redis->hSetJson("remindRent", $this->code . "and" . $v['grid'], 1, $_time);
                                                $content = '交租提醒';
                                                $title = '交租提醒';
                                                $text = '您的生意“' . $v['industry_title'] . '”该交租金了,请您及时处理';
                                                $rep = $a->pushMessageToSingle($content, $title, $text, $this->code);

                                            }
                                            # 超过1天 改为待交租
                                            # 修改为需交租状态
                                            $list[$k]['status'] = 4;
                                            goto taxes;
                                        } else {
                                            # 判断今日是否是否用了恢复券
                                            $restore_material = $this->_Redis->hGetJson("restore_material", strval($v['id']));
                                            if (empty($restore_material)) {
                                                # 改为冻结状态
                                                $list[$k]['status'] = 5;
                                                if ($diff_rent['day'] > 3) {
                                                    $list[$k]['day'] = 3;
                                                } else {
                                                    $list[$k]['day'] = $diff_rent['day'] - 1;// 需要使用几天的恢复材料
                                                }
                                                $diff_rent = timediff(time(), strtotime($v['opera_start_time']));
                                                # 计算应加多长时间
                                                $_duration = date("Y-m-d H:i:s",
                                                    strtotime("+" . ($diff_rent['day'] - 2) . " days +" . $diff_rent['hour'] . " hours +" . $diff_rent['min'] . " minutes +"
                                                        . $diff_rent['min'] . " seconds",
                                                        strtotime($v['sell_time'])
                                                    )
                                                );
                                                $list[$k]['sell_time'] = $_duration;
                                                $list[$k]['opera_end_time'] = date("Y-m-d H:i:s"); // 以当前时间作为标准计算需要加多长时间
                                                Db::table("member_business")->where(array("id" => $v['id']))->update(array("status" => 5, "sell_time" => $list[$k]['sell_time'], "opera_end_time" => $list[$k]['opera_end_time']));
                                            }
                                            continue;
                                        }
                                    }
                                }
                                # 判断出售时间是否大于当前时间
                                if (date("Y-m-d H:i:s") >= $list[$k]['sell_time']) {
                                    $add_diff_day = timediff(time(), strtotime($list[$k]['sell_time']));
                                    $add_day = intval($v['growth_cycle'] - $v['rent_day'] + $add_diff_day['day']) - 1;
                                    $list[$k]['sell_time'] = date("Y-m-d H:i:s", strtotime("+ " . intval($add_day) . " days", strtotime($v['sell_time'])));
                                    $v['sell_time'] = date("Y-m-d H:i:s", strtotime("+ " . intval($add_day) . " days", strtotime($v['sell_time'])));
                                    Db::table("member_business")->where(array("id" => $v['id']))->update(array("sell_time" => $v['sell_time']));
                                }
                            }
                        } elseif ($v['status'] == 7) {
                            # 交易成功待确认 判断是否有审核交易的id
                            if (empty($v['trad_audit_id'])) {
                                $list[$k]['trad_audit_id'] = Db::table("trad_audit")->field("id")
                                    ->where(array("trad_status" => 1, "industry_id" => $v['id']))->order("id desc")->find()['id'];
                            }
                            continue;
                        } elseif ($v['status'] == 8) {
                            # 等待买家付款
                            if (empty($v['buy_code'])) {
                                $list[$k]['buy_code'] = Db::table("member_business_grid")->field("member_code")
                                    ->where(array("sell_business_id" => $v['id'], "status" => 7))->find()['member_code'];
                            }
                            # 查询是否超过2个小时
                            if ($v['opera_end_time'] <= date("Y-m-d H:i:s")) {
                                $list[$k]['status'] = 3;
                                $jobService = new jobService();
                                $jobService->recoverSellStatus($v['id'], $v['grid'], $this->code, $v['buy_code'], $v['buy_grid']);
                            }
                        } elseif ($v['status'] == 5) {
                            $diff_rent = timediff(time(), strtotime($v['opera_start_time']));
                            if ($diff_rent['day'] > 3) {
                                $list[$k]['day'] = 3;
                            } else {
                                $list[$k]['day'] = $diff_rent['day'] - 1;// 需要使用几天的恢复材料
                            }
                            # 计算应加多长时间
                            $_add_diff = time() - strtotime($v['opera_end_time']);
                            $_duration = date("Y-m-d H:i:s", strtotime("+{$_add_diff} seconds", strtotime($v['sell_time'])));
                            $list[$k]['sell_time'] = $_duration;
                            $list[$k]['opera_end_time'] = date("Y-m-d H:i:s"); // 以当前时间作为标准计算需要加多长时间
                            Db::table("member_business")->where(array("id" => $v['id']))->update(array("sell_time" => $list[$k]['sell_time'], "opera_end_time" => $list[$k]['opera_end_time']));
                            $is_remind = $this->_Redis->hGetJson("remind", $this->code);
                            if (empty($is_remind)) {
                                $_time = strtotime(date("Y-m-d 23:59:59")) - time();
                                $this->_Redis->hSetJson("remind", $this->code, 1, $_time);
                                # 向用户发送冻结消息
                                $content = '资产冻结';
                                $title = '资产冻结';
                                $text = '您的资产被冻结了，快去处理吧';
                                $rep = $a->pushMessageToSingle($content, $title, $text, $this->code);
                            }
                            continue;
                        } elseif ($v['status'] == 4) {
                            # 判断需交租天数是否超过两天
                            goto freeze;
                            # 判断需交几天的租
                            taxes:
                            goto earn;
                        } elseif ($v['status'] == 2) {
                            # 可出售状态判断是否是最高级行业  是否已达到满级
                            cansale:
                            $detail = getsIndustryDetail($v['industry_id']);
                            if ($detail['info']['level'] == 12 and ($v['buy_price'] * (1 + ($v['growth_cycle'] * $v['earnings_ratio']))) >= $detail['info']['max_worth']) {
                                $super_business += 1;
                            }
                            if ($detail['info']['category'] == 2) {
                                if (($v['buy_price'] * (1 + ($v['growth_cycle'] * $v['earnings_ratio']))) >= $detail['info']['max_worth']) {
                                    $list[$k]['experience'] = false;
                                } else {
                                    $list[$k]['experience'] = true;
                                }
                            }
                        }
                    }
                }
            } elseif ($v['open_status'] == 3) {
                # 打扫中 判断实际打扫结束时间
                $pract_end_time = diffSuspend($v['start_time'], $v['end_time']);
                $_array = array();
                if ($v['pract_end_time'] != $pract_end_time) {
                    $v['pract_end_time'] = $pract_end_time;
                    $_array['pract_end_time'] = $pract_end_time;
                }
                if (date("Y-m-d H:i:s") >= $v['pract_end_time']) {
                    # 打扫结束 更改状态 并增加无生意计时
                    $list[$k]['open_status'] = 1;
                    $list[$k]['start_time'] = $v['pract_end_time'];
                    $list[$k]['end_time'] = date("Y-m-d H:i:s", strtotime("+3 days", strtotime($v['pract_end_time'])));
                    $list[$k]['pract_end_time'] = date("Y-m-d H:i:s", strtotime("+3 days", strtotime($v['pract_end_time'])));
                    $_array['status'] = 1;
                    $_array['start_time'] = $list[$k]['start_time'];
                    $_array['end_time'] = $list[$k]['end_time'];
                    $_array['pract_end_time'] = $list[$k]['pract_end_time'];
                    $content = '打扫结束';
                    $title = '打扫结束';
                    $text = '您可以购买新的资产了';
                    $rep = $a->pushMessageToSingle($content, $title, $text, $this->code);
                }
                if (!empty($_array)) {
                    Db::table("member_business_grid")->where(array("member_code" => $this->code, "grid" => $v['grid']))->update($_array);
                }
            } else {
                # 已购买待玩家确认状态
                continue;
            }
        }
        $this->_Redis->hSetJson("member_business", $this->code, $list);
        $super_grid = true;
        $super_business = 0;
        if ($super_business == 12) {
            $super_business = true;
        } else {
            $super_business = false;
        }
        if ($super_grid and $super_business) {
            $super_open_status = true;
        } else {
            $super_open_status = false;
        }
        return array("status" => true, "day_income_count" => $day_income, "list" => $list, "super_open" => array("super_open_status" => $super_open_status,
            "super_grid" => $super_grid, "super_business" => $super_business));
    }

    /**
     * @param $bussiness_id
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 查看行业详情
     */
    function getsBusinessDetail($bussiness_id)
    {
        $info = Db::table("industry iu")
            ->field("iu.logo,iu.title,iu.min_worth,iu.max_worth,max(ic.day_income) max_prop,
            min(ic.day_income) min_prop,max(ic.cycle_period) max_period,min(ic.cycle_period) min_period,
                ml.title level_title,iu.desc iu_desc,iu.detail")
            ->join("industry_cycleincome ic", "ic.industry_id=iu.id", "left")
            ->join("member_level ml", "iu.level=ml.id", "left")
            ->where(array("iu.id" => $bussiness_id))
            ->find();
        $info['logo'] = ResourceService::imgUrl($info['logo']);
        return $info;
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 超级玩家生意
     */
    function superPlayer()
    {
        $list = $this->_Redis->hGetJson("superPlayer", $this->code);
        if (empty($list)) {
            $list = Db::table("member_business mb")
                ->field("mb.*")
                ->join("industry indu", "indu.id=mb.industry_id and indu.category=3 and indu.status=1")
                ->where(array("member_code" => $this->code, "place_status" => 1))
                ->find();

        }
        $day_income = 0;
        if ($list['status'] == 1) {
            # 收益中判断是否需要交租
            if ($list['growth_cycle'] == $list['rent_day']) {
                # 已全部交完租 改为已完成状态2
                $list['status'] = 2;
                Db::table("member_business")->where(array("id" => $list['id']))->update(array("status" => 2));
            } else {
                superneedfreeze:
                $diff = timediff(time(), strtotime($list['buy_time']));
                if ($diff['day'] >= $list['growth_cycle']) {
                    $_basic_cycle = $list['growth_cycle'];
                } else {
                    $_basic_cycle = $diff['day'];
                }
                if ($_basic_cycle >= 1) {
                    $diff_day = $_basic_cycle - $list['rent_day'];
                    if ($diff_day > 0) {
                        if ($diff_day > 1) {
                            # 修改状态为冻结5 并暂停收益状态 记录暂停时间 增加间隔时间
                            $_restore = $this->_Redis->hSetJson("restore_material", strval($list['id']));
                            if (empty($_restore)) {
                                $list['status'] = 5;
                                Db::table("member_business")->where(array("id" => $list['id']))->update(array("status" => 5));
                            }
                            $list['day'] = $diff_day;// 需要交几天的租
                            # 计算应加多长时间
                            superfreeze:
                            $_duration = time() - strtotime(date("Y-m-d H:i:s", strtotime("+" . ($list['rent_day'] + 1) . " days", strtotime($list['buy_time']))));
                            $list['sell_time'] = date("Y-m-d H:i:s", strtotime("+ {$_duration} seconds", strtotime($list['opera_end_time'])));
                            Db::table("member_business")->where(array("id" => $list['id']))->update(array("sell_time" => $list['sell_time']));
                        } else {
                            # 修改为需交租金
                            $list['status'] = 4;
                            $list['day'] = 1;// 需要交几天的租
                            goto superfreeze;
                        }

                    } else {
                        # 收益中
                        goto superearn;
                    }
                } else {
                    # 收益中
                    superearn:
                    $day_income += $list['day_income'];
                }
            }
        } elseif ($list['status'] == 5) {
            # 已冻结
            goto superneedfreeze;
        } elseif ($list['status'] == 4) {
            # 判断需交几天的租
            goto superneedfreeze;
        }
        $this->_Redis->hSetJson("superPlayer", $this->code, $list);
        return array("status" => true, "day_income_count" => $day_income, "list" => $list);
    }

    /**
     * @param int $mark
     * @param null $super_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 超级玩家上市、重新开始 回到首页
     */
    function immediatelyOnMark($mark = 1, $super_id = null)
    {
        if (!empty($super_id)) {
            $_old = $this->_Redis->hGetJson("superPlayer", $this->code);
            # 将原来的超级玩家生意删除
            Db::table("member_business")->where(array("id" => $super_id))->update(array("status" => -1));
            # 增加玩家收益
            $this->memberInfo['gold'] += $_old['sale_price'];
            Db::table("member_property")->where(array("member_code" => $this->code))->setInc("gold", $_old['sale_price']);
            $this->_Redis->hSetJson("memberInfo", $this->code, $this->memberInfo);
            # 增加玩家收入记录
            Db::table("log_gold")->insert(array("member_code" => $this->code, "gold_num" => $_old['sale_price'], "type" => 7, "member_business_id" => $_old['id']));
        }
        # 重新开始 或返回首页状态
        if ($mark = 1) {
            if (empty($super_id)) {
                # 更改玩家状态为超级玩家
                Db::table("member")->where(array("code" => $this->code))->update(array("super_player" => 2));
                $this->memberInfo['super_player'] = 2;
                $this->_Redis->hSetJson("memberInfo", $this->code, $this->memberInfo);
            }
            # 超级玩家立即上市
            $list = Db::table("industry")->where(array("category" => 3, "status" => 1))->find();
            $sell_time = date("Y-m-d H:i:s", strtotime("+{$list['income_cycle']} days"));
            $_array = array("member_code" => $this->code, "industry_id" => $list['id'], 'industry_imgurl' => $list['logo'],
                "industry_title" => $list['title'], "day_income" => $list['max_worth'] / $list['income_cycle'], "status" => 1,
                "buy_time" => date("Y-m-d H:i:s"), "sell_time" => $sell_time, "growth_cycle" => $list['income_cycle'], "earnings_price" => $list['max_worth'],
                "sale_price" => $list['max_worth'], "rent_day" => 0, "opera_end_time" => $sell_time, "place_status" => 1, "day_rents" => $list['day_rent']
            );
            $id = Db::table("member_business")->insertGetId($_array);
            $_array['id'] = $id;
            $this->_Redis->hSetJson("superPlayer", $this->code, $_array);
        } else {
            # 返回首页 将用户状态改为普通用户
            Db::table("member")->where(array("code" => $this->code))->update(array("super_player" => 1));
            $this->memberInfo['super_player'] = 1;
            $this->_Redis->hSetJson("memberInfo", $this->code, $this->memberInfo);
        }
        return array("status" => true);
    }

    /**
     * @param $mb_id 玩家生意id
     * @param $gird 栏位
     * @param $day 交多少天的
     * @param $day_price 每日租金
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 摊位交租金
     */
    function payRent($mb_id, $gird, $day_price)
    {
        # 判断用户金币是否足够
        if (($this->memberInfo['gold']+$this->memberInfo['bind_gold']) < $day_price) {
            return array("status" => false, "msg" => "金币不足");
        }
        # 判断绑定金币是否足够
        if($this->memberInfo['bind_gold']>=$day_price){
            Db::table("member_property")->where(array("member_code" => $this->code))->setDec('bind_gold', $day_price);
            # 减少金币
            $this->memberInfo['gold'] -= $day_price;
        }else{
            Db::table("member_property")->where(array("member_code" => $this->code))->update(array('bind_gold'=>0));
            Db::table("member_property")->where(array("member_code" => $this->code))->setDec('gold', ($day_price-$this->memberInfo['bind_gold']));
            $this->memberInfo['gold']-=$day_price-$this->memberInfo['bind_gold'];
            $this->memberInfo['bind_gold'] = 0;
        }

        # 增加交租记录
        # 更改缓存
        $this->_Redis->hSetJson("memberInfo", $this->code, $this->memberInfo);
        $_array = array("member_code" => $this->code, "gold_num" => $day_price, "type" => 8,
            "create_time" => date("Y-m-d H:i:s"), "grid_id" => $gird);
        Db::table("log_gold")->insert($_array);

        $list = $this->_Redis->hGetJson("member_business", $this->code);
        $list[$gird - 1]['status'] = 1;
        $list[$gird - 1]['rent_day'] = intval($list[$gird - 1]['rent_day']) + 1;
        $end_time = date("H:i:s", strtotime($list[$gird - 1]['sell_time']));
        $_opera_start_time = date("Y-m-d {$end_time}");
        $list[$gird - 1]['opera_start_time'] = $_opera_start_time;
        $this->_Redis->hSetJson("member_business", $this->code, $list);
        # 修改数据库中状态
        Db::table("member_business")->where(array("id" => $mb_id))->update(array("status" => 1, "rent_day" => $list[$gird - 1]['rent_day'], "opera_start_time" => $_opera_start_time));
        # 完成任务
        TaskService::finishTask($this->code, 12);
        return array("status" => true);
    }

    /**
     * @param $mb_id 用户生意id
     * @param $gird
     * @param int $perioy
     * @param int $material
     * @return array
     * @throws \think\Exception
     * @context 恢复摊位
     */
    function recoverBussiness($mb_id, $gird, $perioy = 1, $super_player = 1, $material)
    {
        # 查询用户是否有足够的恢复材料
        $num = $this->memberInfo['materials'];
        if ($num >= $material) {
            # 减数据库材料
            $res = Db::table("member_property")->where(array("member_code" => $this->code))->setDec("materials", $material);
            if ($res) {
                $this->memberInfo['materials'] -= $material;
                # 修改缓存
                $this->_Redis->hSetJson("memberInfo", $this->code, $this->memberInfo);
                # 增加记录
                MemberService::addLog_materials($this->code, $material, 2, 2);
                # 查询摊位创建时间
                $member_business_buy_time = Db::table("member_business")->field("sell_time,growth_cycle,rent_day")->where(array("id" => $mb_id))->find();
                # 恢复摊位
                # 计算恢复时间
                $_hour = date("H:i:s");
                $_time = date("Y-m-d {$_hour}", strtotime($member_business_buy_time['sell_time']));
                # 计算距离完成时间还有多少天
                $diff = timediff(time(), strtotime($_time));
                # 计算还需交租多少天
                $diff_rent = $member_business_buy_time['growth_cycle'] - $member_business_buy_time['rent_day'];
                if ($diff_rent > $diff) {
                    $add_day = intval($diff_rent) - intval($diff) - 1;
                    $_time = date("Y-m-d H:i:s", strtotime("+{$add_day} days", strtotime($_time)));
                }
                $_db_time = strtotime("+1 day") - time();
                $this->_Redis->hSetJson("restore_material", strval($mb_id), 1, $_db_time);
                Db::table("member_business")->where(array("id" => $mb_id))->update(array("status" => 4, "sell_time" => $_time));
                # 恢复缓存
                if ($super_player == 1) {
                    $list = $this->_Redis->hGetJson("member_business", $this->code);
                    $list[$gird - 1]['status'] = 4;
                    $list[$gird - 1]['sell_time'] = $_time;
                    $this->_Redis->hSetJson("member_business", $this->code, $list);
                } else {
                    $list = $this->_Redis->hGetJson("superPlayer", $this->code);
                    $list['status'] = 4;
                    $this->_Redis->hSetJson("superPlayer", $this->code, $list);
                }
                return array("status" => true);
            } else {
                return array("status" => false, "msg" => "恢复失败");
            }
        } else {
            return array("status" => false, "msg" => "材料不足");
        }
    }

    /**
     * @return array
     * @context 等级匹配数组
     */
    function matchingLevel()
    {
        return [
            [1],
            [1, 2],
            [1, 2, 3],
            [2, 3, 4],
            [2, 3, 4, 5],
            [3, 4, 5, 6],
            [3, 4, 5, 6, 7],
            [4, 5, 6, 7, 8],
            [4, 5, 6, 7, 8, 9],
            [5, 6, 7, 8, 9, 10],
            [5, 6, 7, 8, 9, 10, 11],
            [6, 7, 8, 9, 10, 11, 12],
        ];
    }

    /**
     * @param $level
     * @return mixed
     * @context 等级对应的匹配等级
     */
    function userMatchingLevel($level)
    {
        $section = $this->matchingLevel();
        return $section[$level];
    }

    /**
     * @param $level
     * @return array|bool|mixed|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 获取行业价值区间 （使用后台设置）
     */
    function getLevelSection($level)
    {
        $list = $this->_Redis->hGetJson("levelSection", $level);
        if (empty($list)) {
            $list = Db::table("industry iu")
                ->field("min(ic.min_num) minvalue,max(ic.max_num) maxvalue")
                ->join("industry_cycleincome ic", "ic.industry_id=iu.id")
                ->where(array("iu.level" => $level))
                ->select();
            if (!empty($list)) {
                $this->_Redis->hSetJson("levelSection", $level, array("minvalue" => $list[0]['minvalue'], "maxvalue" => $list[0]['maxvalue']));
            }
            return array("minvalue" => $list[0]['minvalue'], "maxvalue" => $list[0]['maxvalue']);
        } else {
            return $list;
        }
    }

    /**
     * @return array
     * @context 可参与匹配的价值区间
     */
    function matchValueSection()
    {
        return [
            [200, 2500],
            [200, 3000],
            [200, 3600],
            [200, 4000],
            [200, 4800],
            [200, 5500],
            [200, 6000],
            [400, 7000],
            [400, 8500],
            [400, 10000],
            [400, 12000],
            [600, 15000],
        ];
    }

    /**
     * @param $level
     * @return mixed
     * @context 根据等级获取可参与匹配的价值区间
     *
     */
    function getMatchValueSections($level)
    {
        $list = $this->matchValueSection();
        return $list[$level];
    }

    /**
     * @return array
     * @context 可选择价值区间
     */
    function canUseValueSection()
    {
        return [
            [[200, 500], [500, 1000], [1000, 2000], [2000, 2500]],
            [[200, 900], [900, 1500], [1500, 2200], [2200, 3000]],
            [[200, 900], [900, 1600], [1800, 2600], [2600, 3600]],
            [[400, 1200], [1200, 2000], [2000, 3000], [3000, 4000]],
            [[400, 1500], [1500, 2500], [2500, 3800], [3800, 4800]],
            [[600, 1800], [1800, 3000], [3000, 4200], [4200, 5500]],
            [[600, 2000], [2000, 3500], [3500, 4800], [4800, 6000]],
            [[800, 2200], [2200, 3800], [3800, 5500], [5500, 7000]],
            [[800, 2500], [2500, 4000], [4000, 6000], [6000, 8500]],
            [[1000, 3000], [3000, 5000], [5000, 7500], [7500, 10000]],
            [[1000, 4000], [4000, 7000], [7000, 9000], [9000, 12000]],
            [[1200, 4500], [4500, 8000], [8000, 11500], [11500, 15000]],
        ];
    }

    /**
     * @param $level
     * @return mixed
     * @context 获取等级对应可选价值区间
     */
    function getCanUseValueSection($level)
    {
        $list = $this->canUseValueSection();
        return $list[$level - 1];
    }


    /**
     * @param $grid 栏位
     * @param $data 匹配数据  包括匹配价值区间
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 用户参与匹配
     */
    function participationMatching($grid, $data)
    {
        $jobservice = new jobService();
        return $jobservice->startMatch($this->code, $this->level, $grid, $data, $this->memberInfo['team_id']);
    }

    /**
     * @param $id 用户生意id
     * @param $grid 用户栏位
     * @param $data 用户生意数据
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 出售生意
     */
    function saleBusiness($id, $grid, $data, $mark = 1)
    {
        $business = Db::table("member_business")->field("status,member_code")->where(array("id" => $id))->find();
        if ($business['status'] != 2 && $business['status'] != 1) {
            return array("status" => false, "msg" => "该生意不可出售");
        }
        # 计算可匹配的团队
        # 查询团队可匹配类型
        $team_id = Db::table("member")->field("team_id")->where(array("code" => $business['member_code']))->find();
        $team = Db::table("team")->field("matching_type,team_set")->where(array("id" => $team_id['team_id']))->find();
        if (empty($team)) {
            # 没有团队的情况 默认是按
        }
        if ($team['matching_type'] == 1) {
            $team_set = $team_id['team_id'];
        } else {
            $team_set = $team_id['team_id'] . "," . $team['team_set'];
        }

        # 计算出售金额
        $sale_price = $data['sale_price'];
        if (empty($sale_price)) {
            $sale_price = priceFormat($data['buy_price'] + $data['buy_price'] * $data['earnings_ratio']);
        }
        # 改变用户生意状态
        $res = Db::table("member_business")->where(array("id" => $id))->update(array("status" => 3, "sale_price" => $sale_price, "team_id" => $team_set,
            "earnings_price" => $sale_price - $data['buy_price'], "opera_start_time" => date("Y-m-d H:i:s")));
        if ($res) {
            $data['sale_price'] = $sale_price;
            if (!empty($grid)) {
                $data["sell_grid"] = $grid;
            }
            # 获取用户信息
            $data['sale_member_name'] = $this->memberInfo['name'];
            $data['sale_member_phone'] = $this->memberInfo['phone'];
            # 计算当前出售价格处于哪种收益阶段
            $detail = getsIndustryDetail($data['industry_id']);
            foreach ($detail['cycleIncome'] as $k => $v) {
                if ($v['min_num'] <= $sale_price and $sale_price < $v['max_num']) {
                    $data['cycle_period'] = $v['cycle_period'];
                    $data['now_day_income'] = $v['day_income'];
                    break;
                }
            }

            if ($mark == 2) {
                $ware = $this->_Redis->hGetJson("wareHouse", $this->code);
                $ware[$grid]['status'] = 3;
                $ware[$grid]['sale_price'] = $sale_price;
                $ware[$grid]['team_id'] = $team_set;
                $this->_Redis->hSetJson("wareHouse", $this->code, $ware);
            } else {
                $data['sell_grid'] = $grid;
                # 改变缓存中用户生意状态
                $list = $this->_Redis->hGetJson("member_business", $this->code);
                $list[$grid - 1]['status'] = 3;
                $list[$grid - 1]['sale_price'] = $sale_price;
                $list[$grid - 1]['sale_time'] = date("Y-m-d H:i:s");
                $list[$grid - 1]['team_id'] = $team_set;
                $list[$grid - 1]["earnings_price"] = $sale_price - $data['buy_price'];
                $list[$grid - 1]["opera_start_time"] = date("Y-m-d H:i:s");
                $this->_Redis->hSetJson("member_business", $this->code, $list);

            }
            # 将用户生意信息存入售卖池中
            $sale_list = $this->_Redis->hGetJson("member_sale_bussiness", $data['earnings_level']);
            if (empty($sale_list)) {
                $sale_list = array();
            }
            array_push($sale_list, $data);
            $this->_Redis->hSetJson("member_sale_bussiness", $data['earnings_level'], $sale_list);
            return array("status" => true);
        } else {
            return array("status" => false, "msg" => "出售失败");
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 选择生意
     */
    function chooseBusiness($grid)
    {
        # 获取匹配的数据
        $userMatch = $this->_Redis->hGetJson("userMatchBussiness", $this->code . "and" . $grid);

        if (!empty($userMatch)) {
            $_return = array();
            $fail = array();
            foreach ($userMatch as $k => $v) {
                $member_business = Db::table("member_business")->field("status")->where(array("id" => $v['id']))->find();
                if ($member_business['status'] != 3) {
                    array_push($fail, $v);
                } else {
                    array_unshift($_return, $v);
                }
            }
            if (count($_return) < 3) {
                $fail_sub = array_slice($fail, 0, 3 - count($_return));
                $_return = array_merge($_return, $fail_sub);
            }
            array_multisort(array_column($_return, 'sale_price'), SORT_ASC, $_return);
            $_return_array = array();
            array_push($_return_array, $_return[0]);
            # 中间随机取出一个
            if (count($userMatch) > 4) {
                $middle_array = array_values(array_slice($_return, 2, count($_return) - 4));
            } else {
                $middle_array = array_values(array_slice($_return, 1, count($_return) - 2));
            }
            $rand = rand(0, count($middle_array) - 1);
            array_push($_return_array, $middle_array[$rand]);
            array_push($_return_array, end($_return));
            # 判断是否需要重新匹配
            if (!empty($_return_array)) {
                return array("status" => true, "data" => $_return_array);
            } else {
                $this->anewMatch($this->code, $grid);
                return array("status" => false, "code" => 2, "msg" => "您晚了一步，生意被其他人买走了");
            }
        } else {
            $this->anewMatch($this->code, $grid);
            return array("status" => false, "code" => 2, "msg" => "未匹配到信息");
        }
    }

    /**
     * @param $code
     * @param $grid
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 未匹配到数据改为重新开始匹配
     */
    function anewMatch($code, $grid)
    {
        # q清除用户匹配记录
        $this->_Redis->hDel("userMatchBussiness", $code . "and" . $grid);
        # 清除监听
        $this->_Redis->hDel("matchListen", $code . "and" . $grid);
        # 将用户生意改为可购买
        Db::table("member_business_grid")
            ->where(array("member_code" => $code, "grid" => $grid))
            ->update(array("status" => 1, "end_time" => date("Y-m-d H:i:s", strtotime("+3 days")),
                "pract_end_time" => date("Y-m-d H:i:s", strtotime("+3 days"))));
        $list = $this->_Redis->hGetJson("member_business", $code);
        $list[$grid - 1]['open_status'] = 1;
        $list[$grid - 1]['end_time'] = date("Y-m-d H:i:s", strtotime("+3 days"));
        $list[$grid - 1]['pract_end_time'] = date("Y-m-d H:i:s", strtotime("+3 days"));
        $this->_Redis->hSetJson("member_business", $code, $list);
        return true;
    }

    /**
     * @param $id
     * @param $sale_member_code
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 玩家确认选择生意查看信息
     */
    function tradeInformation($id, $sale_member_code, $data)
    {
        if (empty($data['buy_grid'])) {
            return array("status" => false, "msg" => "该生意不可购买");
        }

        # 查询该信息是否被保护状态
        $protect = $this->_Redis->hGetJson("trade_protect", strval($id));
        if (!empty($protect)) {
            if ($protect['buy_code'] != $this->code) {
                return array("status" => false, "msg" => "该生意已被其他人买走了，请重新选择");
            }
        } else {
            $is_sell = Db::table("member_business")->field("status")->where(array("id" => $id))->find();
            if ($is_sell['status'] != 3) {
                return array("status" => false, "msg" => "该生意已被其他人买走了，请重新选择");
            } else {
                $this->_Redis->hSetJson("trade_protect", strval($id), array("buy_code" => $this->code, "buy_grid" => $data['buy_grid'], "start_time" => date("Y-m-d H:i:s"),
                    "sell_code" => $sale_member_code, "sell_grid" => $data['sell_grid'],
                    "end_time" => date("Y-m-d H:i:s", strtotime("+2 hours"))));
            }
        }

        # 删除用户匹配信息
        $this->_Redis->hDel("userMatchBussiness", $this->code . "and" . $data['buy_grid']);
        # 绑定交易用户栏位
        Db::table("member_business_grid")->where(array("member_code" => $this->code, "grid" => $data['buy_grid']))
            ->update(array("status" => 7, "sell_business_id" => $id, "start_time" => date("Y-m-d H:i:s"), "end_time" => date("Y-m-d H:i:s", strtotime("+2 hours"))));
        $buy_business = $this->_Redis->hGetJson("member_business", $this->code);
        $buy_business[$data['buy_grid'] - 1]['open_status'] = 7;
        $buy_business[$data['buy_grid'] - 1]['sell_business_id'] = $id;
        $buy_business[$data['buy_grid'] - 1]['start_time'] = date("Y-m-d H:i:s");
        $buy_business[$data['buy_grid'] - 1]['end_time'] = date("Y-m-d H:i:s", strtotime("+2 hours"));
        $this->_Redis->hSetJson("member_business", $this->code, $buy_business);

        # 将卖家生意改为等待买家付款
        Db::table("member_business")->where(array("id" => $id))->update(array("status" => 8, "buy_code" => $this->code,
            "opera_start_time" => date("Y-m-d H:i:s"),
            "opera_end_time" => date("Y-m-d H:i:s", strtotime("+2 hours")),
            "buy_grid" => $data['buy_grid']));

        # 向用户发送匹配成功消息
        $a = new IGeTuiService();
        $content = '交易提醒';
        $title = '交易提醒';
        $text = '您的生意出售成功，去查看';
        $rep = $a->pushMessageToSingle($content, $title, $text, $sale_member_code);
        if (!empty($data['sell_grid'])) {
            $sell_business = $this->_Redis->hGetJson("member_business", $sale_member_code);
            $sell_business[$data['sell_grid'] - 1]['status'] = 8;
            $sell_business[$data['sell_grid'] - 1]['buy_code'] = $this->code;
            $sell_business[$data['sell_grid'] - 1]['buy_grid'] = $data['buy_grid'];
            $sell_business[$data['sell_grid'] - 1]['opera_start_time'] = date("Y-m-d H:i:s");
            $sell_business[$data['sell_grid'] - 1]['opera_end_time'] = date("Y-m-d H:i:s", strtotime("+2 hours"));
            $this->_Redis->hSetJson("member_business", $sale_member_code, $sell_business);
        } else {
            $this->_Redis->hDel("wareHouse", $sale_member_code);
        }
        # 将卖家信息在售卖池中删除
        $sale_pool = $this->_Redis->hGetJson("member_sale_bussiness", $data['earnings_level']);
        if (!empty($sale_pool)) {
            foreach ($sale_pool as $k => $v) {
                if ($v['id'] == $id) {
                    unset($sale_pool[$k]);
                    break;
                }
            }
            $this->_Redis->hSetJson("member_sale_bussiness", $data['earnings_level'], $sale_pool);
        }
        $sale_member_info = MemberService::checkMemberRegister($sale_member_code, "account")['info'];
        # 查询售卖用户是否是该用户好友
        $friends = Db::table("friends")->field("id")->where(array("member_code" => $this->code, "friends_code" => $sale_member_code))->find();
        # 是否是好友状态
        $friends_status = false;
        if (!empty($friends)) {
            $friends_status = true;
        }
        # 查询用户是否有可用卡券
        $voucher = Db::table("member_voucher")->where(array("member_code" => $this->code))->where("expiration_time>='" . date("Y-m-d H:i:s") . "' and use_status=1")->count();
        return array("status" => true, "headimg" => $sale_member_info['head_portrait'], "phone" => $sale_member_info['phone'], "hidphone" => hidPhone($sale_member_info['phone']),
            "level_title" => $sale_member_info['title'], "name" => $sale_member_info['name'], "voucher_num" => $voucher, "friends_status" => $friends_status,
            "collection" => array("wx_img" => $sale_member_info["wx_img"], "ali_img" => $sale_member_info['ali_img'],
                "union_name" => $sale_member_info['bank_people'], "union_bank" => $sale_member_info['bank'],
                "union_card" => $sale_member_info['unionpay_number'], "union_bank_address" => $sale_member_info['bank_address'],
                "union_img" => $sale_member_info['union_img']));
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context  确认交易提交
     */
    function confirmTrade($data)
    {
        $is_inner = Db::table("trad_audit")->where(array("buy_code" => $this->code, "industry_id" => $data['id'], "sell_code" => $data['member_code'], "trad_status" => 1))->find();
        if (!empty($is_inner)) {
            return array("status" => true);
        }
        # 查询是否在栏位上
        if (empty($data['sell_grid'])) {
            $member_grid_num = Db::table("member_business_grid")->field("grid")->where(array("member_business_id" => $data['id'], "member_code" => $data['member_code']))->order("id desc")->find();
            if (!empty($member_grid_num)) {
                $data['sell_grid'] = $member_grid_num['grid'];
            }
        }
        # 添加交易信息
        $res = Db::table("trad_audit")->insertGetId(array("buy_code" => $this->code, "buy_name" => $this->memberInfo['name'], "buy_phone" => $this->memberInfo['phone'],
            "industry_id" => $data['id'], "price" => $data['pract_price'], "screenshot" => ResourceService::uploadBase($data['screenshot']),
            "sell_code" => $data['member_code'], "sell_name" => $data['sale_member_name'], "sell_phone" => $data['sale_member_phone'],
            "trad_time" => date("Y-m-d H:i:s"), "trad_status" => 1, "amount" => $data['amount'], "voucher_id" => $data['voucher_id'], "voucher_price" => $data['voucher_price'],
            "voucher_title" => $data['voucher_title'], "pay_type" => $data['pay_type'], "sell_grid" => $data['sell_grid'], "buy_grid" => $data['buy_grid'], "confirm_buy_time" => date("Y-m-d H:i:s")));
        if ($res) {
            # 修改卖家 信息为待确认
            Db::table("member_business")->where(array("id" => $data['id']))->update(array("status" => 7, "trade_time" => date("Y-m-d H:i:s"), "trad_audit_id" => $res, 'opera_end_time' => date("Y-m-d H:i:s", strtotime("+2 hours"))));
            $mark = 2; // 是栏位 还是仓库标识
            if (!empty($data['sell_grid'])) {
                $mark = 1;
                # 修改卖家缓存信息为待确认
                $sell_info = $this->_Redis->hGetJson("member_business", $data['member_code']);
                $sell_info[$data["sell_grid"] - 1]['status'] = 7;
                $sell_info[$data["sell_grid"] - 1]['trade_time'] = date("Y-m-d H:i:s");
                $sell_info[$data["sell_grid"] - 1]['trad_audit_id'] = $res;
                $sell_info[$data["sell_grid"] - 1]['opera_end_time'] = date("Y-m-d H:i:s", strtotime("+2 hours"));
                $this->_Redis->hSetJson("member_business", $data['member_code'], $sell_info);
            } else {
                $this->_Redis->hDel("wareHouse", $data['member_code']);
            }
            # 修改买家栏位为待卖家确认
            Db::table("member_business_grid")->where(array("member_code" => $this->code, "grid" => $data['buy_grid']))
                ->update(array("status" => 6, "sell_business_id" => $res, "start_time" => date("Y-m-d H:i:s"),
                    "end_time" => date("Y-m-d H:i:s", strtotime("+2 hours"))));
            $buy_info = $this->_Redis->hGetJson("member_business", $this->code);
            $buy_info[$data["buy_grid"] - 1]['open_status'] = 6;
            $buy_info[$data["buy_grid"] - 1]['member_business_id'] = 0;
            $buy_info[$data["buy_grid"] - 1]['sell_business_id'] = $res;    // 添加的是交易信息id
            $buy_info[$data["buy_grid"] - 1]['start_time'] = date("Y-m-d H:i:s");    // 添加的是交易信息id
            $buy_info[$data["buy_grid"] - 1]['end_time'] = date("Y-m-d H:i:s", strtotime("+2 hours"));    // 添加的是交易信息id
            $this->_Redis->hSetJson("member_business", $this->code, $buy_info);
            # 删除买家栏位匹配中数据
            $this->_Redis->hDel("userMatchBussiness", $this->code . "and" . $data['buy_grid']);
            # 删除该生意的交易保护
            $this->_Redis->hDel("trade_protect", strval($data['id']));
            # 增加生意确认两小时定时任务
            $this->_Redis->hSet("timedTask", strval($data['id']), json_encode(array("sell_code" => $data['member_code'], "sell_grid" => $data['sell_grid'],
                "buy_code" => $this->code, "buy_grid" => $data['buy_grid'], "complaint" => 1, "trad_audit_id" => $res,
                "start_time" => date("Y-m-d H:i:s"), "end_time" => date("Y-m-d H:i:s", strtotime("+2 hours")), "mark" => $mark)));
            # 将该生意在售卖池中删除
            $sale_array = $this->_Redis->hGetJson("member_sale_bussiness", $data['earnings_level']);
            if (!empty($sale_array)) {
                foreach ($sale_array as $k => $v) {
                    if ($v['id'] == $data['id']) {
                        unset($sale_array[$k]);
                        break;
                    }
                }
                $this->_Redis->hSetJson("member_sale_bussiness", $data['earnings_level'], array_values($sale_array));
            }
            if (!empty($data['voucher_id'])) {
                Db::table("member_voucher")->where(array("id" => $data['voucher_id']))->update(array("use_status" => 2));
            }
            # 给对方发送 付款成功提醒
            $getui = new IGeTuiService();
            $getui->pushMessageToSingle('付款成功提醒', '付款成功', '您有一个生意被别人买走了,赶快查看收益吧', $data['member_code'], 2);
            return array("status" => true);
        } else {
            return array("status" => false, "msg" => "系统错误");
        }
    }

    /**
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 卖家确认交易查看信息
     */
    function successInformation($id)
    {

        $list = Db::table("trad_audit")->where(array("id" => $id))->find();
        if (!empty($list)) {
            # 获取买家信息
            $sale_member_info = MemberService::checkMemberRegister($list['buy_code'], "account")['info'];
            # 查询售卖用户是否是该用户好友
            $friends = Db::table("friends")->field("id")->where(array("member_code" => $this->code, "friends_code" => $list['buy_code']))->find();
            # 是否是好友状态
            $friends_status = false;
            if (!empty($friends)) {
                $friends_status = true;
            }
            return array(
                "status" => true, "headimg" => $sale_member_info['head_portrait'], "hidphone" => hidPhone($list['buy_phone']), "phone" => $list['buy_phone'],
                "level_title" => $sale_member_info['title'], "name" => $sale_member_info['name'], "friends_status" => $friends_status,
                "sale_price" => $list['price'], "amount" => $list['amount'], "voucher_title" => $list['voucher_title'], "voucher_id" => $list['voucher_id'],
                "voucher_price" => $list['voucher_price'],
                "pay_type" => $list['pay_type'], "cert" => imgUrl($list['screenshot']), "id" => $list['id'], "business_id" => $id
            );
        }
    }

    /**
     * @param $id   交易审核的id
     * @param int $main
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 获取对方信息
     */
    function checkTradeInfomation($id, $main = 1)
    {
        $list = Db::table("trad_audit")->where(array("id" => $id))->find();
        if (!empty($list)) {
            if ($main == 1) {
                # 我是买家 获取卖家信息
                $sub_code = $list['sell_code'];
            } else {
                # 我是卖家获取买家信息
                $sub_code = $list['buy_code'];
            }
            # 获取对方信息
            $sale_member_info = MemberService::checkMemberRegister($sub_code, "account")['info'];
            # 查询售卖用户是否是该用户好友
            $friends = Db::table("friends")->field("id")->where(array("member_code" => $this->code, "friends_code" => $sub_code))->find();
            # 是否是好友状态
            $friends_status = false;
            if (!empty($friends)) {
                $friends_status = true;
            }
            return array(
                "status" => true, "headimg" => $sale_member_info['head_portrait'], "hidphone" => hidPhone($sale_member_info['phone']), "phone" => $sale_member_info['phone'],
                "level_title" => $sale_member_info['title'], "name" => $sale_member_info['name'], "friends_status" => $friends_status,
                "sell_business_id" => $list['industry_id'], "trad_time" => $list['trad_time']
            );
        }
    }

    /**
     * @param $buy_code
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 等待买家付款
     */
    function waitBuyerPayment($buy_code)
    {
        # 获取对方信息
        $sale_member_info = MemberService::checkMemberRegister($buy_code, "account")['info'];
        # 查询售卖用户是否是该用户好友
        $friends = Db::table("friends")->field("id")->where(array("member_code" => $this->code, "friends_code" => $buy_code))->find();
        # 是否是好友状态
        $friends_status = false;
        if (!empty($friends)) {
            $friends_status = true;
        }
        return array(
            "status" => true, "headimg" => $sale_member_info['head_portrait'], "hidphone" => hidPhone($sale_member_info['phone']), "phone" => $sale_member_info['phone'],
            "level_title" => $sale_member_info['title'], "name" => $sale_member_info['name'], "friends_status" => $friends_status
        );
    }

    /**
     * @param $member_business_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 等待付款 查看信息
     */
    function waitPayment($member_business_id)
    {

        $list = Db::table("member_business mb")
            ->field("mb.*,m.name sale_member_name,m.phone sale_member_phone")
            ->join("member m", "m.code=mb.member_code", "left")
            ->where(array("mb.id" => $member_business_id))
            ->find();
        $list['industry_imgurl'] = imgUrl($list['industry_imgurl']);
        return array("status" => true, "data" => $list);
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 玩家确认交易
     */
//    function successTrade($data)
//    {
//        $sell_list=Db::table("member_bussiness")->where(array("id"=>$data['sell_id']))->find();
//        # 卖家生意改为已出售
//        Db::table("member_bussiness")->where(array("id"=>$data['sell_id']))->update(array("status"=>-1,"trade_finish_time"=>date("Y-m-d H:i:s")));
//        if(!empty($data['sell_grid'])){
//            # 卖家生意和栏位解绑     # 卖家栏位改为打扫中
//            Db::table("mebmer_bussiness_grid")->where(array("member_code"=>$data['sell_code'],"grid"=>$data['sell_grid']))
//                ->update(array("member_business_id"=>0,"status"=>3));
//            # 更改卖家栏位缓存
//            $sell_member_bussiness=$this->_Redis->hGetJson("member_business",$data['sell_code']);
//            $sell_member_bussiness[$data['sell_grid']-1]=array("open_status"=>3,"grid"=>$data['sell_grid']);
//            $this->_Redis->hSetJson("member_business",$data['sell_code'],$sell_member_bussiness);
//        }
//        # 删除定时任务
//        $this->_Redis->hDel("timedTask",strval($data['sell_id']));
//        # 买家卡券转移给卖家
//        if(!empty($data['voucher_id'])){
//            $voucher_info=Db::table("member_voucher")->where(array("id"=>$data['voucher_id']))->find();
//            # 修改为已使用
//            Db::table("member_voucher")->where(array("id"=>$data['voucher_id']))->update(array("use_status"=>2));
//            # 给卖家增加一张卡券
//            unset($voucher_info['id']);
//            $voucher_info['member_code']=$data['buy_code'];
//            $voucher_info['expiration_time']=date("Y-m-d H:i:s",strtotime("+".$voucher_info['voucher_perioy']." days"));
//            $voucher_info['get_time']=date("Y-m-d H:i:s");
//            $voucher_info['source']=2;
//            Db::table("member_voucher")->insert($voucher_info);
//        }
//        # 买家生意和栏位绑定
//        # 计算当前出售价格处于哪种收益阶段
//        $detail=$this->_Redis->hGetJson("industryDetail",strval($data['industry_id']));
//        foreach($detail['cycleIncome'] as $k=>$v){
//            if($v['min_num']<=$data['amount'] and $data['amount']<$v['max_num']){
//                $data['cycle_period']=$v['cycle_period'];
//                $data['day_income']=$v['day_income'];
//                break;
//            }
//        }
//        # 给玩家添加生意
//        $_array=array("member_code"=>$data["buy_code"],"industry_id"=>$sell_list['industry_id'],"industry_imgurl"=>$sell_list['industry_imgurl'],
//            "industry_title"=>$sell_list['industry_title'],"day_income"=>intval($data['day_income']*$data['amount']),
//            "status"=>1,"buy_time"=>date("Y-m-d H:i:s"),"sell_time"=>date("Y-m-d H:i:s",strtotime("+".$data['cycle_period']." days")),
//            "growth_cycle"=>$data['cycle_period'],"earnings_ratio"=>$data['day_income'],"earnings_level"=>$sell_list['earnings_level'],
//            "buy_price"=>$data['amount']);
//        $buy_business_id=Db::table("member_business")->insertGetId($_array);
//        $_array['id']=$buy_business_id;
//        # 关联买家生意到买家栏位
//        Db::table("member_business_grid")->where(array("member_code"=>$data['buy_code'],"grid"=>$data['buy_grid']))
//            ->update(array("member_business_id"=>$buy_business_id));
//        # 更改买家栏位缓存
//        $buy_member_business=$this->_Redis->hGetJson("member_business",$data['buy_code']);
//        $buy_member_business[$data['buy_grid']-1]=array_merge(array("open_status"=>1,"grid"=>$data['buy_grid']),$_array);
//        $this->_Redis->hSetJson("member_business",$data['buy_code'],$buy_member_business);
//        # 添加交易记录
//        Db::table("log_trad")->insert(array("seller_code"=>$data['sell_code'],"buyer_code"=>$data['buy_code'],
//            "industry_id"=>$sell_list['industry_id'],"sell_price"=>$data['amount'],"buy_price"=>$data['price'],"industry_imgurl"=>$sell_list['industry_imgurl'],
//            "industry_title"=>$sell_list['industry_title'],"growth_cycle"=>$sell_list['growth_cycle'],"earnings_ratio"=>$sell_list['earnings_ratio'],
//            "earnings_price"=>$sell_list['sale_price']-$sell_list['buy_price'],"sell_time"=>$sell_list['trade_time'],"buy_time"=>$data['confirm_buy_time'],
//            "member_business_id"=>$sell_list['id'],"buyer_business_id"=>$buy_business_id,"voucher_id"=>$data['voucher_id'],"voucher_title"=>$data['voucher_title'],
//            "voucher_price"=>$data['voucher_price']));
//        # 更改交易审核状态
//        Db::table("trad_audit")->where(array("id"=>$data['id']))->update(array("trad_status"=>2));
//        # 给团队加提成
//        # 获取该等级下提成比例
//        $deduct=jobService::getLevelDeduct($sell_list['earnings_level']);
//        # 获取售卖人的上级
//        $sell_p_code=Db::table("member")->field("p_code")->where(array("code"=>$data['sell_code']))->find()['p_code'];
//        if(!empty($sell_p_code)){
//            # 增加父级成交金额比例的金币 加金币记录
//            $p_gold=$sell_list['sale_price']*$deduct[0];
//            Db::table("member_property")->where(array("member_code"=>$sell_p_code))->setInc("gold",$p_gold);
//            $p_info=$this->_Redis->hGetJson("memberInfo",$sell_p_code);
//            $p_info['gold']+=$p_gold;
//            $this->_Redis->hSetJson("memberInfo",$sell_p_code,$p_info);
//            Db::table("log_gold")->insert(array("member_code"=>$sell_p_code,"gold_num"=>$p_gold,"type"=>7,"member_business_id"=>$sell_list['id']));
//            # 查询祖父级
//            $sell_gp_code=Db::table("member")->field("p_code")->where(array("code"=>$sell_p_code))->find()['p_code'];
//            if(!empty($sell_gp_code)){
//                $gp_gold=$sell_list['sale_price']*$deduct[1];
//                Db::table("member_property")->where(array("member_code"=>$sell_gp_code))->setInc("gold",$gp_gold);
//                $gp_info=$this->_Redis->hGetJson("memberInfo",$sell_gp_code);
//                $gp_info['gold']+=$gp_gold;
//                $this->_Redis->hSetJson("memberInfo",$sell_gp_code,$gp_info);
//                Db::table("log_gold")->insert(array("member_code"=>$sell_gp_code,"gold_num"=>$gp_gold,"type"=>7,"member_business_id"=>$sell_list['id']));
//            }
//        }
//        return array("status"=>true);
//    }

    function successTrade($data)
    {
        $jobService = new jobService();
        return $jobService->successTrade($data);
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 玩家投诉举报
     */
    function complaintReporting($data)
    {
        # 添加投诉审核
        $res = Db::table("complaint")->insert(array("buy_code" => $data['buy_code'], "buy_name" => $data['buy_name'], "buy_phone" => $data['buy_phone'],
            "industry_id" => $data['industry_id'], "screenshot" => $data['screenshot'], "sell_code" => $data['sell_code'], "sell_name" => $data['sell_name'],
            "sell_phone" => $data['sell_phone'], "create_time" => date("Y-m-d H:i:s"), "reason" => $data['reason'], "complaint_context" => $data['complaint_context'],
            "trad_audit_id" => $data['id']));
        if ($res) {
            # 将交易审核状态改为被投诉
            Db::table("trad_audit")->where(array("id" => $data['id']))->update(array("complaint" => 2));
            # 修改定时任务为投诉状态
            $list = $this->_Redis->hGet("timedTask", strval($data['id']));
            $list['complaint'] = 2;
            $this->_Redis->hSet("timedTask", strval($data['id']), $list);
            return array("status" => true);
        } else {
            return array("status" => false, "msg" => "系统错误");
        }
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 再次出售
     */
    function tradAgain($data)
    {
        $list = $this->_Redis->hGetJson("trade_protect", strval($data['id']));
        # 更改买家栏位绑定状态
        Db::table("member_business_grid")->where(array("member_code" => $list['buy_code'], "grid" => $list['buy_grid']))
            ->update(array("status" => 1, "sell_business_id" => 0));
        $buy_business = $this->_Redis->hGetJson("member_business", $list['buy_code']);
        $buy_business[$list['buy_grid'] - 1]['open_status'] = 1;
        $buy_business[$list['buy_grid'] - 1]['sell_business_id'] = 0;
        $this->_Redis->hSetJson("member_business", $list['buy_code'], $buy_business);
        # 计算当前出售价格处于哪种收益阶段
        $detail = getsIndustryDetail($data['industry_id']);
        foreach ($detail['cycleIncome'] as $k => $v) {
            if ($v['min_num'] <= $data['sale_price'] and $data['sale_price'] < $v['max_num']) {
                $data['cycle_period'] = $v['cycle_period'];
                $data['day_income'] = $v['day_income'];
                break;
            }
        }
        $data['sell_member_name'] = $this->memberInfo['name'];
        $data['sell_member_phone'] = $this->memberInfo['phone'];
        if (!empty($data['sell_grid'])) {
            # 更改卖家栏位状态
            Db::table("member_business_grid")->where(array("member_code" => $this->code, "grid" => $data['sell_grid']))->update(array("status" => 1));
            $sell_business = $this->_Redis->hGetJson("member_business", $this->code);
            $sell_business[$data['sell_grid'] - 1]['open_status'] = 1;
            $sell_list[$data['sell_grid'] - 1]['status'] = 3;
            $sell_list[$data['sell_grid'] - 1]['sale_price'] = $data['sale_price'];
            $sell_list[$data['sell_grid'] - 1]['sale_time'] = date("Y-m-d H:i:s");
            $sell_list[$data['sell_grid'] - 1]['team_id'] = $data['team_id'];
            $this->_Redis->hSetJson("member_business", $this->code, $sell_business);
        }
        # 更改卖家生意状态
        Db::table("member_business")->where(array("id" => $data['id']))->update(array("status" => 3));
        # 删除交易保护
        $this->_Redis->hDel("trade_protect", strval($data['id']));
        # 放入交易池
        # 将用户生意信息存入售卖池中
        $sale_list = $this->_Redis->hGetJson("member_sale_bussiness", $data['earnings_level']);
        if (empty($sale_list)) {
            $sale_list = array();
        }
        array_push($sale_list, $data);
        $this->_Redis->hSetJson("member_sale_bussiness", $data['earnings_level'], $sale_list);
        return array("status" => true);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 仓库列表
     */
    function wareHouseList()
    {
        $list = $this->_Redis->hGetJson("wareHouse", $this->code);
        if (empty($list)) {
            $list = Db::table("member_business")->where(array("place_status" => 2, "member_code" => $this->code))->where("status!=-1")->select();
        }

        if (!empty($list)) {
            return array("status" => true, "list" => $this->wareHouseSettle($list));
        } else {
            return array("status" => false, "msg" => "仓库是空的");
        }

    }

    /**
     * @param $list
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 仓库列表整理
     */
    private function wareHouseSettle($list)
    {
        foreach ($list as $k => $v) {
            # 计算生意当前价值 为购买价格+日收益*交租天数
            if ($list[$k]['status'] == 1) {
                $list[$k]['currentValue'] = $v['buy_price'] + $v['day_income'] * $v['rent_day'];
            } else {
                $list[$k]['currentValue'] = $v['sale_price'];
            }

            $list[$k]['choose'] = false;
            if ($v['status'] == 7) {
                # 待确认状态
                if (empty($v['trad_audit_id'])) {
                    $list[$k]['trad_audit_id'] = Db::table("trad_audit")->field("id")
                        ->where(array("trad_status" => 1, "industry_id" => $v['id']))->order("id desc")->find()['id'];
                }
                continue;
            } elseif ($v['status'] == 8) {
                # 等待买家付款
                if (empty($v['buy_code'])) {
                    $list[$k]['buy_code'] = Db::table("member_business_grid")->field("member_code")
                        ->where(array("sell_business_id" => $v['id'], "status" => 7))->find()['member_code'];
                }
            }
        }
        $this->_Redis->hSetJson("wareHouse", $this->code, $list);
        return $list;
    }

    /**
     * @param $grid
     * @param $business_id
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 从栏位移动到仓库
     */
    function moveToWare($grid, $business_id)
    {
        $grid_list = $this->_Redis->hGetJson("member_business", $this->code);
        if ($grid_list[$grid - 1]['status'] != 2) {
            return array("status" => false, "msg" => "该生意不可移动至仓库");
        } else {
            $data = $grid_list[$grid - 1];
            # 获取行业最大值
            $max_worth = getsIndustryDetail($data['industry_id']);
            if ($data['sale_price'] < $max_worth['info']['max_worth']) {
                return array("status" => false, 'msg' => '该生意不可移动至仓库');
            }
            # 更改用户生意位置
            Db::table("member_business")->where(array("id" => $business_id))->update(array("place_status" => 2));
            $_array = array("member_business_id" => 0, "status" => 1, "start_time" => date("Y-m-d H:i:s"));

            # 更改用户栏位绑定状态
            $res = Db::table("member_business_grid")->where(array("id" => $grid_list[$grid - 1]['mbg_id']))
                ->update($_array);
            # 更改用户生意缓存状态
            $_array['open_status'] = 1;
            $_array["mbg_id"] = $grid_list[$grid - 1]['mbg_id'];
            $_array["grid"] = $grid;
            $_array['status'] = 1;
            $grid_list[$grid - 1] = $_array;
            $this->_Redis->hSetJson("member_business", $this->code, $grid_list);
            # 更改用户仓库列表
            $ware_list = $this->_Redis->hGetJson("wareHouse", $this->code);
            if (!empty($ware_list)) {
                array_push($ware_list, $data);
                $this->_Redis->hSetJson("wareHouse", $this->code, $ware_list);
            }
            return array("status" => true);
        }
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 从仓库移动到栏位
     */
    function shiftToWare($data)
    {
        //$data=array(array("key"=>1,"business_id"=>1,"status"=>1),array("key"=>2,"business_id"=>2，,"status"=>1),array("key"=>3,"business_id"=>3，,"status"=>1));
        # 判断用户状态是否被锁定
        if ($this->memberInfo['member_violations'] == 2) {
            return array("status" => false, "msg" => "交易状态锁定");
        }
        # 判断用户是否有足够的空余栏位
        $grid_leisure = Db::table("member_business_grid")->field("id,grid")->where(array("member_code" => $this->code, "status" => 1, "member_business_id" => 0))->limit(count($data))->select();
        if (count($grid_leisure) < count($data)) {
            return array("status" => false, "msg" => "栏位不够了,请重新选择");
        } else {
            $_continue = true;
            foreach ($data as $k => $v) {
                if ($v['status'] != 1) {
                    $_continue = false;
                    break;
                }
            }
            if (!$_continue) {
                return array("status" => false, "msg" => "包含不可移动的项目,请重新选择");
            } else {
                # 获取玩家生意列表
                $grid_list = $this->_Redis->hGetJson("member_business", $this->code);
                # 获取玩家仓库列表
                $ware_list = $this->_Redis->hGetJson("wareHouse", $this->code);
                foreach ($data as $k => $v) {

                    $sell_time = date("Y-m-d H:i:s", strtotime("+{$ware_list[$v['key']]['growth_cycle']} days"));
                    $sale_price = $ware_list[$v['key']]['buy_price'] * (1 + $ware_list[$v['key']]['earnings_ration']);
                    $earnings_price = priceFormat($sale_price - $ware_list[$v['key']]['buy_price']);
                    $_mapping_data = array("place_status" => 1, "buy_time" => date("Y-m-d H:i:s"),
                        "sell_time" => $sell_time, "opera_end_time" => $sell_time, "sale_price" => $sale_price, "opera_start_time" => date("Y-m-d H:i:s"));
                    # 改变玩家生意位置
                    Db::table("member_business")->where(array("id" => $v['id']))->update($_mapping_data);
                    # 绑定玩家生意到栏位
                    Db::table("member_business_grid")->where(array("id" => $grid_leisure[$k]['id']))->update(array("member_business_id" => $v['id']));
                    # 更改玩家生意缓存
                    $ware_list[$v['key']]['place_status'] = 1;
                    $ware_list[$v['key']]['buy_time'] = date("Y-m-d H:i:s");
                    $ware_list[$v['key']]['sell_time'] = $sell_time;
                    $ware_list[$v['key']]['opera_end_time'] = $sell_time;
                    $ware_list[$v['key']]['sale_price'] = $sale_price;
                    $ware_list[$v['key']]['earnings_price'] = $earnings_price;
                    $grid_list[$grid_leisure[$k]['grid'] - 1] = array_merge($grid_list[$grid_leisure[$k]['grid'] - 1], $ware_list[$v['key']]);
                    $grid_list[$grid_leisure[$k]['grid'] - 1]['buy_time'] = date("Y-m-d H:i:s");
                    $grid_list[$grid_leisure[$k]['grid'] - 1]['opera_start_time'] = date("Y-m-d H:i:s");
                    $grid_list[$grid_leisure[$k]['grid'] - 1]['sell_time'] = $sell_time;
                    $grid_list[$grid_leisure[$k]['grid'] - 1]['opera_end_time'] = $sell_time;
                    $grid_list[$grid_leisure[$k]['grid'] - 1]['sale_price'] = $sale_price;
                    $grid_list[$grid_leisure[$k]['grid'] - 1]['earnings_price'] = $earnings_price;

                    unset($ware_list[$v['key']]);
                }
                $this->_Redis->hSetJson("member_business", $this->code, $grid_list);
                $this->_Redis->hSetJson("wareHouse", $this->code, array_values($ware_list));
                return array("status" => true);
            }
        }

    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 批量出售生意
     */
    function batchSaleBusiness($data)
    {
        //$data=array(array("key"=>1,"business_id"=>1,"status"=>1),array("key"=>2,"business_id"=>2，,"status"=>1),array("key"=>3,"business_id"=>3，,"status"=>1));
        if ($this->memberInfo['member_violations'] == 2) {
            return array("status" => false, "msg" => "交易状态锁定");
        } else {
            # 判断生意状态
            $_continue = true;
            foreach ($data as $k => $v) {
                if ($v['status'] != 2 && $v['status'] != 1) {
                    $_continue = false;
                    break;
                }
            }
            if ($_continue) {
                # 获取玩家仓库列表
                $ware_list = $this->_Redis->hGetJson("wareHouse", $this->code);
                foreach ($data as $k => $v) {
                    $this->saleBusiness($v['id'], $v['key'], $ware_list[$v['key']], 2);
                }
                return array("status" => true);
            } else {
                return array("status" => false, "msg" => "包含不可出售项目，请重新选择");
            }
        }
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 玩家生意升级
     */
    function upgradeBusiness($data)
    {
        if ($this->memberInfo['member_violations'] == 2) {
            return array("status" => false, "msg" => "交易状态锁定");
        } else {
            # 判断生意状态
            $_continue = true;
            $ware = $this->_Redis->hGetJson("wareHouse", $this->code);
            foreach ($data as $k => $v) {
                if ($v['status'] != 2) {
                    $_continue = false;
                    break;
                } else {
                    $_industry = getsIndustryDetail($ware[$v['key']]['industry_id']);
                    if ($_industry['info']['level'] == 12) {
                        $_continue = false;
                        break;
                    } else {
                        if ($ware[$v['key']]['buy_price'] * (1 + ($ware[$v['key']]['growth_cycle'] * $ware[$v['key']]['earnings_ratio'])) < $_industry['info']['max_worth']) {
                            $_continue = false;
                            break;
                        }
                    }
                }
            }
            if ($_continue) {
                $_return = array();
                foreach ($data as $k => $v) {
                    # 查询下一个等级是什么行业
                    $_next_industry = Db::table("industry")->field("id")->where(array("level" => $ware[$v['key']]['earnings_level'] + 1, "is_del" => 2, "status" => 1))->find();

                    # 获取行业信息
                    $_next_info = getsIndustryDetail($_next_industry['id']);
                    $day_income = 0;
                    $cycle_period = 0;
                    foreach ($_next_info['cycleIncome'] as $nk => $nv) {
                        if ($nv['min_num'] <= $ware[$v['key']]['sale_price'] and $ware[$v['key']]['sale_price'] < $nv['max_num']) {
                            $cycle_period = $nv['cycle_period'];
                            $day_income = $nv['day_income'];
                            break;
                        }
                    }
                    # 修改用户生意信息
                    $day_income_per = priceFormat($day_income * $ware[$v['key']]['buy_price'] / $cycle_period);
                    $_array = array("member_code" => $this->code, "industry_id" => $_next_industry['id'], "industry_imgurl" => $_next_info['info']['logo'],
                        "industry_title" => $_next_info['info']['title'],
                        "day_income" => $day_income_per,
                        "status" => 1, "buy_time" => date("Y-m-d H:i:s"), "sell_time" => date("Y-m-d H:i:s", strtotime("+" . $cycle_period . " days")),
                        "growth_cycle" => $cycle_period, "earnings_ratio" => $day_income, "earnings_level" => $_next_info['info']['level'],
                        "buy_price" => $ware[$v['key']]['sale_price'],
                        "sale_price" => priceFormat($ware[$v['key']]['sale_price'] * $day_income),
                        "opera_end_time" => date("Y-m-d H:i:s", strtotime("+" . $cycle_period . " days")),
                        "place_status" => 2,
                        "rent_day" => 0,
                        "day_rents" => priceFormat($day_income_per * $_next_info['info']['day_rent']));

                    Db::table("member_business")->where(array("id" => $ware[$v['key']]['id']))->update($_array);
                    $_array['industry_imgurl'] = imgUrl($_array['industry_imgurl']);
                    array_push($_return, $_array);
                    # 修改缓存信息
                    $ware[$v['key']] = $_array;
                }
                $this->_Redis->hSetJson("wareHouse", $this->code, array_values($ware));
                return array("status" => true, "data" => $_return);
            } else {
                return array("status" => false, "msg" => "包含不可升级项目，请重新选择");
            }
        }

    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 用户生意分解
     */
    function resolveBusiness($data)
    {
        # 判断锁定状态
        if ($this->memberInfo['member_violations'] == 2) {
            return array("status" => false, "msg" => "交易状态锁定");
        } else {
            # 判断生意状态  # 判断是否可以分解
            $_continue = true;
            $ware = $this->_Redis->hGetJson("wareHouse", $this->code);
            foreach ($data as $k => $v) {
                if ($v['status'] != 2) {
                    $_continue = false;
                    break;
                } else {
                    $_industry = getsIndustryDetail($ware[$v['key']]['industry_id']);
                    if ($ware[$v['key']]['buy_price'] * (1 + ($ware[$v['key']]['growth_cycle'] * $ware[$v['key']]['earnings_ratio'])) < $_industry['info']['max_worth']) {
                        $_continue = false;
                        break;
                    }

                }
            }
            if ($_continue) {
                $_return_array = array();
                $_industry_info = getsIndustryDetail($ware[$v['key']]['industry_id']);
                $_detail = $_industry_info['cycleIncome'];
                foreach ($data as $k => $v) {
                    # 选择的等级相等的
                    $sale_price = $ware[$v['key']]['sale_price'];
                    $_need_section = array();
                    $_section = $_detail;
                    foreach ($_section as $sk => $sv) {
                        # 获取区间需求数量
                        $num = $this->_Redis->hGet(strval($ware[$v['key']]['earnings_level']), $sv['min_num'] . 'and' . $sv['max_num']);
                        if (empty($num)) {
                            $num = 0;
                        }
                        # 获取区间售卖数量
                        $sale_list = $this->_Redis->hGetJson("member_sale_bussiness", strval($ware[$v['key']]['earnings_level']));
                        if (empty($sale_list)) {
                            $_sale_num = 0;
                        } else {
                            $sale_price_array = array_column($sale_list, 'sale_price');
                            $_sale_num = count(array_filter($sale_price_array, function ($sale_price_array) use ($sv) {
                                if ($sv['min_num'] <= $sale_price_array and $sale_price_array < $sv['max_num']) {
                                    return true;
                                }
                            }));
                        }
                        array_push($_need_section, array("diff" => $num - $_sale_num, "min" => $sv['min_num'], "max" => $sv['max_num'], "level" => $ware[$v['key']]['earnings_level']));

                    }

                    # 去除是负数的 # 进行排序
                    $_need_section = array_filter($_need_section, function ($_need_section) {
                        return $_need_section['diff'] >= 0;
                    });
                    array_multisort(array_column($_need_section, 'diff'), SORT_DESC, $_need_section);
                    # 获取最小价值区间
                    $_min_section = $_need_section;
                    array_multisort(array_column($_min_section, 'min'), SORT_ASC, $_min_section);
                    $mapping = $_need_section;
                    $choose_industry = array();
                    $_now_value = $sale_price;
                    $_time = 1;
                    while ($_now_value > 0 and $_time < 3) {
                        if (!empty($mapping)) {
                            if (count($choose_industry) == 1) {
                                array_push($choose_industry, array("level" => $mapping[0]['level'], "value" => $_now_value));
                                break;
                            }
                            if (intval(($mapping[0]['min'] + $mapping[0]['max']) / 2) <= $_now_value) {
                                # 价值区间在行业售价50% 以下的
                                $_value = intval(($mapping[0]['min'] + $mapping[0]['max']) / 2);
                                # 如果当前剩余价值减掉当前区间小于最小区间价值
                                if ($_now_value - $_value < $_min_section[0]['min']) {
                                    # 将剩余价值填入
                                    array_push($choose_industry, array("level" => $mapping[0]['level'], "value" => $_now_value));
                                    break;
                                } else {
                                    array_push($choose_industry, array("level" => $mapping[0]['level'], "value" => $_value));
                                    $_now_value -= $_value;
                                    unset($mapping[0]);
                                    $_time++;
                                }
                            } else {
                                unset($mapping[0]);
                            }
                        } else {
                            break;
                        }
                        $mapping = array_values($mapping);
                    }
                    # 添加用户仓库生意
                    foreach ($choose_industry as $cik => $civ) {
                        $_detailed = $_detail;
                        $_detail_choose = array_values(array_filter($_detailed, function ($_detailed) use ($civ) {
                            if ($civ['value'] < $_detailed['max_num'] and $civ['value'] >= $_detailed['min_num']) {
                                return true;
                            } else {
                                return false;
                            }
                        }));
                        # 查询对应等级的生意
                        array_push($_return_array, array("member_code" => $this->code, "industry_id" => $ware[$v['key']]['industry_id'],
                            "industry_imgurl" => $_industry_info['info']['logo'],
                            "industry_title" => $_industry_info['info']['title'],
                            "day_income" => priceFormat($civ['value'] * $_detail_choose[0]['day_income'] / $_detail_choose[0]['cycle_period']),
                            "status" => 1, "buy_time" => date("Y-m-d H:i:s"), "sell_time" => date("Y-m-d H:i:s", strtotime("+" . $_detail_choose[0]['cycle_period'] . " days")),
                            "growth_cycle" => $_detail_choose[0]['cycle_period'], "earnings_ratio" => $_detail_choose[0]['day_income'], "earnings_level" => $_industry_info['info']['level'],
                            "buy_price" => $civ['value'],
                            "sale_price" => $civ['value'],
                            "earnings_price" => $civ['value'],
                            "opera_end_time" => date("Y-m-d H:i:s", strtotime("+" . $_detail_choose[0]['cycle_period'] . " days")),
                            "place_status" => 2,
                            "rent_day" => 0,
                            "day_rents" => priceFormat($civ['value'] * $_detail_choose[0]['day_income'] / $_detail_choose[0]['cycle_period'] * $_industry_info['info']['day_rent'])));

                    }
                    Db::table("member_business")->where(array("id" => $v['id']))->update(array("status" => -1));
                }
                Db::table("member_business")->insertAll($_return_array);
                # 删除用户仓库生意缓存
                $this->_Redis->hDel("wareHouse", $this->code);
                array_walk($_return_array, function (&$value) {
                    $value['industry_imgurl'] = imgUrl($value['industry_imgurl']);
                });
                return array("status" => true, "data" => $_return_array);
            } else {
                return array("status" => false, "msg" => "包含不可分解项目，请重新选择");
            }
        }
    }

    /**
     * @param $business_id
     * @param $grid
     * @param int $mark
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 玩家体验行业兑换卡券
     */
    function businessConversionVoucher($business_id, $grid, $mark = 1)
    {
        # 更改玩家生意
        $res = Db::table("member_business")->where(array("id" => $business_id))->update(array("status" => -1));
        if ($res) {
            # 给玩家加卡券
            $voucher = Db::table("voucher")->where(array("id" => 1))->find();
            $_array = array();
            for ($i = 0; $i < 2; $i++) {
                array_push($_array, array("member_code" => $this->code, "voucher_title" => $voucher['title'], "voucher_id" => 1, "price" => $voucher['price'],
                    "expiration_time" => date("Y-m-d H:i:s", strtotime("+15 days")), "get_time" => date("Y-m-d H:i:s"), "source" => 3, "source_branch" => 6,
                    "voucher_perioy" => 15));
            }
            Db::table("member_voucher")->insertAll($_array);
            if ($mark == 1) {
                # 更改卖家栏位缓存
                $sell_member_bussiness = $this->_Redis->hGetJson("member_business", $this->code);
                $sell_member_bussiness[$grid - 1] = array("mbg_id" => $sell_member_bussiness[$grid - 1]['mbg_id'], "open_status" => 3, "grid" => $grid,
                    "start_time" => date("Y-m-d H:i:s"),
                    "end_time" => date("Y-m-d H:i:s", strtotime("+3 hours")),
                    "pract_end_time" => date("Y-m-d H:i:s", strtotime("+3 hours")));

                $this->_redis->hSetJson("member_business", $this->code, $sell_member_bussiness);
            } else {
                # 更改玩家仓库列表
                $ware_list = $this->_Redis->hGetJson("wareHouse", $this->code);
                unset($ware_list[$grid]);
                $this->_Redis->hSetJson("member_business", $this->code, array_values($ware_list));
            }
        } else {
            return array("status" => false, "msg" => "兑换错误");
        }
    }

    /**
     * @param $currentLevel
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 查询下个等级的生意
     */
    function checkNextLevel($currentLevel)
    {
        # 查询下一个等级是什么行业
        $_next_industry = Db::table("industry")->field("id")->where(array("level" => intval($currentLevel) + 1, "is_del" => 2, "status" => 1))->find();
        # 获取行业信息
        $_next_info = getsIndustryDetail($_next_industry['id']);
        return array("status" => true, "data" => array("industry_title" => $_next_info['info']['title'], "industry_imgurl" => imgUrl($_next_info['info']['logo']),
            "price" => $_next_info['info']['min_worth']));
    }

    /**
     * @return array
     * @context 玩家生意列表
     */
    function myBusinessList()
    {
        $_business_list = $this->_Redis->hGetJson("member_business", $this->code);
        if (!empty($_business_list)) {
            $_business_list = array_filter($_business_list, function ($v) {
                return $v['member_business_id'] != 0;
            });
        } else {
            $_business_list = array();
        }
        $wareHouse = $this->_Redis->hGetJson("wareHouse", $this->code);
        if (!empty($wareHouse)) {
            $_business_list = array_merge(array_values($_business_list), $wareHouse);
        }
        return array("status" => true, "data" => array_values($_business_list));
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 获取玩家冻结之后需要恢复的信息
     */
    function getsMemberRecoverInfo()
    {
        $info = Db::table("member_business_grid mbg")
            ->field("mb.day_income,mb.growth_cycle")
            ->join("member_business mb", "mbg.member_business_id=mb.id and mb.rent_day<=mb.growth_cycle and mb.place_status=1 and mb.status!=-1")
            ->where(array('mbg.member_code' => $this->code))
            ->where("mbg.member_business_id!=0")
            ->select();
        $_count = 0;
        if (!empty($info)) {
            foreach ($info as $k => $v) {
                $_count += $v['day_income'] * $v['growth_cycle'];
            }
        }
        $_need = ceil($_count * 0.2);
        # 判断是否存在交易厅投诉
        $tradingInfo = Db::table('trading_room')
            ->field('num,type')
            ->where("find_in_set(id,(select trading_room_id from member_property where member_code = '" . $this->code . "'))")
            ->select();
        if (!empty($tradingInfo)) {
            foreach ($tradingInfo as $k => $v) {
                if ($v['type'] == 1) {
                    # 金币 , 1恢复券=2金币
                    $_need = priceFormat($_need + ($v['num'] / 2));
                } else {
                    # 积分  1金币 = 4积分 , 1恢复券 = 8 积分
                    $_need = priceFormat($_need + ($v['num'] / 8));
                }
            }
        }
        # 起步10恢复券
        $_need = $_need > 10 ? $_need : 10;

        return array("status" => true, "count" => $_count, "need" => $_need);

    }

    /**
     * @param $need
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 用户恢复冻结状态
     */
    function memberRecover($need)
    {
        # 查询玩家是否有足够的恢复券
        $materials = Db::table("member_property")->field("materials")->where(array("member_code" => $this->code))->find()['materials'];
        if ($materials < $need) {
            return array("status" => false, "msg" => "恢复券不足");
        }
        # 扣除玩家恢复券
        Db::table("member_property")->field("materials")->where(array("member_code" => $this->code))->setDec('materials', $need);
        $this->memberInfo['materials'] -= $need;
        # 增加使用记录
        MemberService::addLog_materials($this->code, intval($need), 2, 2);
        # 更改用户状态
        Db::table("member")->where(array("code" => $this->code))->update(array("member_violations" => 1));
        # 清空 交易厅投诉
        Db::table("member_property")->where(array("member_code" => $this->code))->update(array("trading_room_id" => 0));
        $this->memberInfo['member_violations'] = 1;
        $this->_Redis->hSetJson("memberInfo", $this->code, $this->memberInfo);
        # 增加恢复缓存
        $_time = strtotime(date("Y-m-d 23:59:59")) - time();
        $this->_Redis->hSetJson("restore_material_system", $this->code, 1, $_time);
        return array("status" => true);
    }

    /**
     * @param $grid
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 刷新用户单个栏位
     */
    function reflushMemberGrid($grid)
    {
        $list = $this->getsMemberBusiness();
        return array("status" => true, "day_income_count" => $list['day_income_count'], "list" => $list['list'][$grid - 1]);
    }


    function canPurchaseService($id)
    {
        # 查询该信息是否被保护状态
        $protect = $this->_Redis->hGetJson("trade_protect", strval($id));
        if (!empty($protect)) {
            if ($protect['buy_code'] != $this->code) {
                return array("status" => false, "msg" => "该生意已被其他人买走了，请重新选择");
            }
        } else {
            $is_sell = Db::table("member_business")->field("status")->where(array("id" => $id))->find();
            if ($is_sell['status'] != 3) {
                return array("status" => false, "msg" => "该生意已被其他人买走了，请重新选择");
            }
        }
        return array("status" => true);
    }
}